package org.example.ui;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ClickSpeedCounter extends Application {
    private long startTime;
    private long endTime;
    int clickCount = 0;
    double avgClickSpeed = 0.0;
    Text clickText, speedText;

    @Override
    public void start(Stage primaryStage) {

        // 创建GUI界面
        clickText = new Text("点击次数: 0");
        speedText = new Text("平均每分钟点击速度: 0.0");

        HBox hbox = new HBox(clickText, speedText);
        hbox.setSpacing(20.0);
        hbox.setAlignment(Pos.CENTER);

        VBox vbox = new VBox(hbox);
        vbox.setAlignment(Pos.CENTER);

        Scene scene = new Scene(vbox, 400, 200);

        // 创建时间轴，定期更新计数器和平均速度
        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.001), event -> updateAvgClickSpeed()));
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();

        // 设置点击事件
        scene.setOnMouseClicked(event -> {
            handleMouseClick();
        });

        primaryStage.setTitle("点击速度统计器");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    /** 计算平均每分钟点击速度 */
    public void updateAvgClickSpeed() {
        if (clickCount > 0) {
            endTime = System.currentTimeMillis();
            double timeDiffInSeconds = (endTime - startTime) / 1000.0;
            avgClickSpeed = (60.0 * clickCount) / timeDiffInSeconds;
            speedText.setText(String.format("平均每分钟点击速度: %.2f", avgClickSpeed));
        }
    }

    /** 处理点击事件 */
    public void handleMouseClick() {
        if (clickCount == 0) {
            startTime = System.currentTimeMillis();
        }
        clickCount++;
        clickText.setText("点击次数: " + clickCount);

        updateAvgClickSpeed();
    }
}
